
package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.base.ResponseResult;
import com.crm.domain.dto.GiveBusinessDto;
import com.crm.domain.dto.QueryBusiness;
import com.crm.domain.entity.Assignment;
import com.crm.domain.entity.Business;
import com.crm.domain.entity.BusinessPool;
import com.crm.mapper.AssignmentMapper;
import com.crm.mapper.BusinessMapper;
import com.crm.service.BusinessService;
import com.crm.service.IBusinessPoolService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Hulunico
 * @since 2024-08-06
 */

@Service
@RequiredArgsConstructor
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    private final BusinessMapper businessMapper;
    @Override
    public Page<Business> getByPage(QueryBusiness queryBusiness) {
        //1.设置分页参数
        /*
            请求list和请求分页都是同一个接口 如果不对空值进行初始化 会有空指针异常。
            解决方式:手动设置初始值 但ObjectUtil.isEmpty会把null也判断为对象 需要取值或者queryDictType==null
            处理 params 映射时发生的空指针异常
         */
        Page<Business> page = ObjectUtil.isEmpty(queryBusiness.getPageNum())?Page.of(1, 10):Page.of(queryBusiness.getPageNum(), queryBusiness.getPageSize());

        //2.调用Mapper查询数据
        //2.1构建查询条件
        Map<String, Object> params = queryBusiness.getParams();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


        LocalDate beginCreateTime =ObjectUtil.isEmpty(params.get("beginCreateTime"))?null:(LocalDate.parse((String)params.get("beginCreateTime"), formatter));
        LocalDate endCreateTime =ObjectUtil.isEmpty(params.get("endCreateTime"))?null:(LocalDate.parse((String)params.get("endCreateTime"), formatter));


        LambdaQueryWrapper<Business> wrapper = Wrappers.<Business>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(queryBusiness.getId()),Business::getId, queryBusiness.getId())
                .eq(ObjectUtil.isNotEmpty(queryBusiness.getPhone()),Business::getPhone, queryBusiness.getPhone())
                .eq(ObjectUtil.isNotEmpty(queryBusiness.getStatus()),Business::getStatus, queryBusiness.getStatus())
                .like(ObjectUtil.isNotEmpty(queryBusiness.getName()),Business::getName, queryBusiness.getName())
                .between(ObjectUtil.isNotEmpty(beginCreateTime)&&ObjectUtil.isNotEmpty(endCreateTime)
                        ,Business::getCreateTime, beginCreateTime, endCreateTime);

        //2.2用m-plus查询
        Page<Business> businessPage = page(page, wrapper);

        return businessPage;
    }

    /**
     * 分配商机思路：
     *
     * @param
     * @return
     */

    private final AssignmentMapper assignmentMapper;
    @Override
    public ResponseResult assignment(GiveBusinessDto dto) {
        //判断dto非空
        if (ObjectUtil.isEmpty(dto)||ObjectUtil.isEmpty(dto.getIds())){
            return ResponseResult.error("参数为空");}

        int count = 0;
        //为每个商机 ID 创建一个 Assignment 实体，并设置相关属性
      dto.getIds().forEach(id -> {
            Assignment assignment =new Assignment();
            assignment.setUserId(dto.getUserId());
            assignment.setBusinessId(id);
            assignment.setCreateTime(LocalDateTime.now());
            assignment.setUpdateTime(LocalDateTime.now());
           assignmentMapper.insert(assignment);

          List<Business> businesses = businessMapper.selectBatchIds(dto.getIds());
          businesses.forEach(business ->
              business.setStatus("2"));
          updateBatchById(businesses);



      });
        return ResponseResult.success();
    }

    private final IBusinessPoolService businessPoolService;
    @Override
    public ResponseResult kickBack(Long id, Long reasonId) {
        if(ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(reasonId)){
            throw new RuntimeException("参数为空");
        }
        Business business = getById(id);
        BusinessPool businessPool = BeanUtil.copyProperties(business, BusinessPool.class);
        businessPool.setCreateTime(LocalDateTime.now());
        boolean save = businessPoolService.save(businessPool);
        if(!save){
            throw new RuntimeException("保存失败");
        }
        boolean removeById = removeById(id);
        if(!removeById){
            throw new RuntimeException("删除失败");
        }

        return ResponseResult.success();
    }



}

